/* $RCSFile: Portals.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/PortalsAdmin/Portals.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:22  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:58  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.Core;
using AddonNice.Settings;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.Helpers;
using AddonNice.Configuration;
using AddonNice.Diagnostics;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.PortalsAdmin
{
 	#region Local TraceSwitch 
	public class PortalsTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("PortalsTrace","Special Trace Switch for Portals");
	}
	#endregion Local TraceSwitch 

    /// <summary>
    /// Module to manage portals (AdminAll)
    /// </summary>
    public partial class Portals : PortalModuleControl
    {
        PortalsDB portalsDb     =   new PortalsDB();
		CrmDB CrmManDB          =   new CrmDB();
   		
		/// <summary>
		/// Admin Module
		/// </summary>
		public override bool AdminModule
		{
			get
			{
				return true;
			}
		}
		
		public override Guid GuidID 
		{
			get
			{
				return new Guid("{366C247D-4CFB-451D-A7AE-649C83B05841}");
			}
		}

        /// <summary>
        /// The Page_Load server event handler on this user control is used
        ///  to populate the current portals list from the database
        /// </summary>
        private void Page_Load(object sender, System.EventArgs e) 
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose || PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals Page_Load BEG IsPostBack: {0}",IsPostBack),(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:PortalsTrace.Sw.Info);
        }
       
        void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
        {
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_DeleteCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),PortalsTrace.Sw.Info);
            GridDataItem dataItem   =   (GridDataItem)e.Item;
            if (e.Item.OwnerTableView.Name != "Alias")
            {
                int portalID        =   (int)dataItem.GetDataKeyValue("PortalID");
                try
                {
                    portalsDb.DeletePortal(portalID);
                }
                catch (Exception ex)
                {
                    if (PortalsTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Portals RadGrid1_DeleteCommand Error deleting portalId: {0}, ex: {1}", portalID, ex), PortalsTrace.Sw.Info);
                    throw;
                }
                return;
            }
            GridDataItem parentItem = (GridDataItem)(e.Item.OwnerTableView.ParentItem);
            string strPortalId      =   string.Empty;
            if (parentItem != null)
            {
               strPortalId          =   (string)(parentItem.OwnerTableView.DataKeyValues[parentItem.ItemIndex][ "PortalID"]);
            }

            if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_DeleteCommand  strPortalId: {0}",strPortalId),PortalsTrace.Sw.Info);
            try
            {
                int wportalID       =   int.Parse(strPortalId);
                string Alias        =   (string)dataItem.GetDataKeyValue("PortalAlias");
			    if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_DeleteCommand Alias: {0}",Alias),PortalsTrace.Sw.Info);
                portalsDb.DeletePortalAlias(wportalID,Alias);
			    if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_DeleteCommand END portalID: {0}, Alias: {1}",wportalID,Alias),PortalsTrace.Sw.Info);
            }
            catch (Exception ex)
            {
				if (PortalsTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Portals RadGrid1_DeleteCommand ex: {0}",ex),PortalsTrace.Sw.Info);
                throw;
            }

            if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Portals RadGrid1_DeleteCommand END.",PortalsTrace.Sw.Info);
        }

        void RadGrid1_DataBound(object sender,EventArgs e)
        {
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_DataBound BEG RadGrid1.Items.Count: {0}",RadGrid1.Items.Count),PortalsTrace.Sw.Info);
            if ( RadGrid1.Items.Count > 0 )
            {
                RadGrid1.Items[0].Selected                          =   true;
                int PrtID                                           =   (int)RadGrid1.SelectedValue;
                RefreshCommands(PrtID);
            }
            else
            {
                RadGrid2.MasterTableView.CommandItemDisplay         =   GridCommandItemDisplay.None;
            }
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Portals RadGrid1_DataBound END.",PortalsTrace.Sw.Info);
        }

        void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_ItemDataBound BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),PortalsTrace.Sw.Info);
            if (e.Item.OwnerTableView.Name == "Alias"
                || !( e.Item is GridEditableItem ) )
                return;
            GridEditableItem Item       =   e.Item as GridEditableItem;
		    if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_ItemDataBound Item.IsInEditMode: {0}",Item.IsInEditMode),PortalsTrace.Sw.Info);
            if (Item.IsInEditMode)
            {
                GridEditFormItem ftem   =   e.Item as GridEditFormItem;
                string sType            =   ((Label)(ftem.ParentItem.FindControl("LblType"))).Text;
			    if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_ItemDataBound sType: {0}",sType),PortalsTrace.Sw.Info);
                CheckBoxList CbType     =   (CheckBoxList)ftem.FindControl("CbType");
                if ( sType.IndexOf("MultiCrmServer") > -1 ) 
                    CbType.Items[0].Selected    =   true;
                if ( sType.IndexOf("MultiOrganization") > -1 ) 
                    CbType.Items[1].Selected    =   true;
            }
            else
            {
                Label Lbl               =   (Label)Item.FindControl("LblType");
                if (Lbl != null)
                {
                    string sType        =   Lbl.Text;
                    PortalType pType    =   (PortalType)int.Parse(sType);
                    if (PortalsTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_ItemDataBound pType: {0}", pType), PortalsTrace.Sw.Info);
                    Lbl.Text            =   pType.ToString();
                }
            }

        }

        void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
        {
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_UpdateCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),PortalsTrace.Sw.Info);
            GridEditableItem editedItem =   e.Item as GridEditableItem;
            Hashtable newValues         =   new Hashtable();
            if (e.Item.OwnerTableView.Name != "Alias")
            {
                e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                try
                {
                    int xportalID           =   (int)(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][ "PortalID"]);
                    string portalName       =   (string)newValues["PortalName"];
                    string portalPath       =   (string)newValues["PortalPath"];
                    CheckBoxList cbType     =   (CheckBoxList)editedItem.FindControl("CbType");
                    PortalType pType        =   PortalType.MonoServer;
                    if (cbType.Items[0].Selected )
                        pType        |=   PortalType.MultiCrmServer;
                    if (cbType.Items[1].Selected )
                        pType        |=   PortalType.MultiOrganization;
                    portalsDb.UpdatePortal2(xportalID,portalName,portalPath,(int)pType);
			        if (PortalsTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_UpdateCommand END portalID: {0}, portalName: {1}",xportalID,portalName),PortalsTrace.Sw.Info);
                }
                catch (Exception ex)
                {
				    if (PortalsTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Portals RadGrid1_UpdateCommand ex: {0}",ex),PortalsTrace.Sw.Info);
                    throw;
                }
                return;
            }

            GridDataItem parentItem = (GridDataItem)(e.Item.OwnerTableView.ParentItem);
            int wportalID           =   (int)(parentItem.OwnerTableView.DataKeyValues[parentItem.ItemIndex][ "PortalID"]);
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_UpdateCommand strPortalId: {0}",wportalID),PortalsTrace.Sw.Info);
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);

            try
            {
                string oldAlias  =   (string)e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["PortalAlias"];
                string newAlias  =   (string)newValues["PortalAlias"];
			    if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_UpdateCommand oldAlias: {0}, newAlias: {1}",oldAlias,newAlias),PortalsTrace.Sw.Info);
                portalsDb.UpdatePortalAlias(wportalID,oldAlias,newAlias);
			    if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_UpdateCommand END portalID: {0}, newAlias: {1}",wportalID,newAlias),PortalsTrace.Sw.Info);
            }
            catch (Exception ex)
            {
				if (PortalsTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Portals RadGrid1_UpdateCommand ex: {0}",ex),PortalsTrace.Sw.Info);
                throw;
            }
        }

        private void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_InsertCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),PortalsTrace.Sw.Info);
            if ( e.Item.OwnerTableView.Name != "Alias" )
                return;
            GridEditableItem editedItem =   e.Item as GridEditableItem;

            GridDataItem parentItem     =   (GridDataItem)(e.Item.OwnerTableView.ParentItem);
            int wportalID               =   (int)(parentItem.OwnerTableView.DataKeyValues[parentItem.ItemIndex][ "PortalID"]);
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_InsertCommand strPortalId: {0}",wportalID),PortalsTrace.Sw.Info);
            Hashtable newValues         =   new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);

            try
            {
                string newAlias         =   (string)newValues["PortalAlias"];
			    if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_InsertCommand newAlias: {0}",newAlias),PortalsTrace.Sw.Info);
                portalsDb.AddPortalAlias(wportalID,newAlias);
			    if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_InsertCommand END portalID: {0}, newAlias: {1}",wportalID,newAlias),PortalsTrace.Sw.Info);
            }
            catch (Exception ex)
            {
				if (PortalsTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Portals RadGrid1_InsertCommand ex: {0}",ex),PortalsTrace.Sw.Info);
                throw;
            }
        }
        
        void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_ItemCommand CommandName: {0}, SelectedIndexes.Count: {1}",
                    e.CommandName,RadGrid1.SelectedIndexes.Count),PortalsTrace.Sw.Info);
            if ( e.CommandName == "EditSelectedPortal")
            {
                if (RadGrid1.SelectedIndexes.Count == 0)
                    return;
                GridDataItem item       =  (GridDataItem )RadGrid1.SelectedItems[0];
                int portalID            =   (int)item.GetDataKeyValue("PortalID");
                string str              =   string.Format("portalid={0}&mid={1}", portalID, ModuleID);
                ADNPage.Redirect(HttpUrlBuilder.BuildUrlWithCustomAttributes(Config.ModulesPath+"/PortalsAdmin/EditPortal.aspx",PageID,str),true);
            }
            else if ( e.CommandName == "AddNewPortal" )
            {
                ADNPage.Redirect(HttpUrlBuilder.BuildUrlWithCustomAttributes(AddUrl,PageID,"mID=" + ModuleID.ToString()),true);;
            }
        }

        #region Grid methods

        void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            if (e.IsFromDetailTable)
                return;
            try
			{
				RadGrid1.DataSource	=	portalsDb.GetPortalsTb();
			}
			catch(Exception ex)
			{
				if (PortalsTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Portals Page_Load ex: {0}",ex),PortalsTrace.Sw.Info);
                throw;
			}
        }

        void RadGrid2_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid2_NeedDataSource BEG Reason: {0}.",e.RebindReason),PortalsTrace.Sw.Info);
            try
            {
                int PortalId        =   (RadGrid1.SelectedValue == null ) ? -1:(int)RadGrid1.SelectedValue;
			    if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid2_NeedDataSource PortalId: {0}.",PortalId),PortalsTrace.Sw.Info);
                RadGrid2.DataSource =   CrmManDB.GetCrmServerByPortalTb(PortalId);
            }
            catch ( Exception ex )
            {
			    if (PortalsTrace.Sw.TraceError)
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[E]Portals RadGrid2_NeedDataSource ex: {0}.",ex),PortalsTrace.Sw.Info);
                throw;
            }
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Portals RadGrid2_NeedDataSource END .",PortalsTrace.Sw.Info);
        }

        void RefreshCommands(int PrtID)
        {
            int CountOther                                      =   0;
            int Count                                           =   CrmManDB.ExistPortalsByCrmServer(PrtID,ref CountOther);
            if ( CountOther > 0 ) // No more new entities, not necessary to offered adding 
                    RadGrid2.MasterTableView.CommandItemDisplay =   GridCommandItemDisplay.Top;
            else    RadGrid2.MasterTableView.CommandItemDisplay =   GridCommandItemDisplay.None;
        }

        void RadGrid1_SelectedIndexChanged(object sender,EventArgs e)
        {
            bool hasSel                                             =   RadGrid1.SelectedValue != null ;
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_SelectedIndexChanged BEG hasSel: {0}.",hasSel),PortalsTrace.Sw.Info);
            if ( !hasSel  )
            {
                RadGrid2.MasterTableView.CommandItemDisplay         =   GridCommandItemDisplay.None;
            }
            else
            {
                int CrmServerID                                     =   (int)RadGrid1.SelectedValue;
                RefreshCommands(CrmServerID);
            }
            RadGrid2.Rebind();
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Portals RadGrid1_SelectedIndexChanged END.",PortalsTrace.Sw.Info);
        }

        void RadGrid1_DetailTableDataBind(object source, GridDetailTableDataBindEventArgs e)
        {
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_DetailTableDataBind BEG e.DetailTableView.ParentItem: {0}",
                    e.DetailTableView.ParentItem),PortalsTrace.Sw.Info);
            GridDataItem dataItem           =   (GridDataItem)e.DetailTableView.ParentItem;
            int pID                         =   (int)dataItem.GetDataKeyValue("PortalID");
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_DetailTableDataBind PortalId: {0}",pID),PortalsTrace.Sw.Info);
            DataTable Tb                    =   portalsDb.GetPortalAliasTb(pID);
            e.DetailTableView.DataSource    =   Tb;
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid1_DetailTableDataBind END Tb.Rows: {0}",Tb.Rows.Count),PortalsTrace.Sw.Info);
        }

        void RadGrid2_ItemDataBound(object sender, GridItemEventArgs e)
        {
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Portals RadGrid2_ItemDataBound BEG.",PortalsTrace.Sw.Info);
            if ( !( e.Item is GridEditableItem ) )
                return;
            GridEditableItem Item                           =   e.Item as GridEditableItem;
		    if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid2_ItemDataBound Item.IsInEditMode: {0}",Item.IsInEditMode),PortalsTrace.Sw.Info);
            if (Item.IsInEditMode)
            {
                DataRowView rw                              =   null;
                if ( !Item.OwnerTableView.IsItemInserted )
                    rw                                      =   (DataRowView)e.Item.DataItem;
                GridEditManager editMan                     =   Item.EditManager;

                GridDropDownListColumnEditor editor         =   (GridDropDownListColumnEditor)editMan.GetColumnEditor( "CrmServer" );
                //in case you have RadComboBox editor for the GridDropDownColumn (this is the default editor),         
                //you will need to use ComboBoxControl below instead of DropDownListControl
                //Then you can modify the list control as per your custom conventions
                try
                {
                    DataTable Tb                            =   CrmManDB.GetAllCrmServerTb();
                    Tb.Columns.Add("CrmServer",typeof(string));
                    foreach ( DataRow vrw in Tb.Rows )
                    {
                        vrw["CrmServer"]                    =   string.Format("{0}/{1}",vrw["DiscoServer"],vrw["Organization"]);
                    }
                    editor.DataSource                       =   Tb;
                    editor.DataBind();
                    if (rw != null)
                    {
                        RadComboBoxItem it                  =   editor.ComboBoxControl.Items.FindItemByValue(rw["CrmServerId"].ToString());
                        if (it != null)
                            it.Selected                     =   true;
                    }
                }
                catch ( Exception ex )
                {
				    if (PortalsTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Portals RadGrid2_ItemDataBound ex: {0}",ex),PortalsTrace.Sw.Info);
                    throw;
                }
            }
            else
            {
                DataRowView rw                              =   (DataRowView)e.Item.DataItem;
                string val                                  =   rw["CrmServerId"].ToString();
                if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid2_ItemDataBound val: {0}",val),PortalsTrace.Sw.Info);
                Item["CrmServer"].Text                      =   val;
            }

        }

        private void RadGrid2_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid2_InsertCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),PortalsTrace.Sw.Info);
            GridEditableItem Item       =   e.Item as GridEditableItem;

            if ( RadGrid1.SelectedValue == null )
            {
			    if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]Portals RadGrid2_InsertCommand END No Portal selected cancelling.",PortalsTrace.Sw.Info);
                e.Canceled              =   true;
                return;
            }

            int PortalId                =   (int)RadGrid1.SelectedValue;
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid2_InsertCommand PortalId: {0}",PortalId),PortalsTrace.Sw.Info);
            Hashtable newValues         =   new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, Item);

            try
            {
                int CrmServerId         =   int.Parse(newValues["CrmServerId"].ToString()); // yes it is the int value from the RadComboBox
			    if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid2_InsertCommand CrmServerId: {0}",CrmServerId),PortalsTrace.Sw.Info);
                DBCrmServer objSrv      =   CrmManDB.GetCrmServerObj(CrmServerId);
                CrmManDB.AddPortalCrmServer(CrmServerId,PortalId,(objSrv.MainPortalID == -1));
                RefreshCommands(PortalId);
			    if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid2_InsertCommand END PortalId: {0}, CrmServerId: {1}",PortalId,CrmServerId),PortalsTrace.Sw.Info);
            }
            catch (Exception ex)
            {
				if (PortalsTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Portals RadGrid2_InsertCommand ex: {0}",ex),PortalsTrace.Sw.Info);
                throw;
            }
        }
        
        void RadGrid2_DeleteCommand(object source,GridCommandEventArgs e)
        {
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Portals RadGrid2_DeleteCommand BEG.",PortalsTrace.Sw.Info);
            GridEditableItem Item       =   e.Item as GridEditableItem;

            int PortalId                =   (int)(Item.OwnerTableView.DataKeyValues[Item.ItemIndex][ "PortalID"]);
            int CrmServerId             =   (int)(Item.OwnerTableView.DataKeyValues[Item.ItemIndex][ "CrmServerId"]);
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Portals RadGrid2_DeleteCommand PortalId: {0}, CrmServerId: {1}",PortalId,CrmServerId),PortalsTrace.Sw.Info);
            try
            {
                CrmManDB.DeletePortalCrmServer(CrmServerId,PortalId);
                RefreshCommands(PortalId);
            }
            catch (Exception ex)
            {
				if (PortalsTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Portals RadGrid2_DeleteCommand ex: {0}",ex),PortalsTrace.Sw.Info);
                throw;
            }
        }

        void RadGrid2_ItemCommand(object source,GridCommandEventArgs e)
        {
	        if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_ItemCommand BEG CommandName: {0}.",e.CommandName),PortalsTrace.Sw.Info);
            if ( e.CommandName == "InstallCrmOrg" )
            {
                int CrmServerId     =   (RadGrid2.SelectedValue == null ) ? -1:(int)RadGrid2.SelectedValue;
                int PortalId        =   (RadGrid1.SelectedValue == null ) ? -1:(int)RadGrid1.SelectedValue;
                if (PortalsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_ItemCommand CrmServerId: {0}.",CrmServerId),PortalsTrace.Sw.Info);
                if (( CrmServerId != -1 ) && ( PortalId != -1) )
                {
                    string Url      =   Config.ModulesPath+"/CrmServerManager/InstallCrmOrg.aspx";
                    Url             =   HttpUrlBuilder.BuildUrlWithCustomAttributes(Url, PageID,string.Format("mId={0}&CrmServerId={1}&portalid={2}",ModuleID,CrmServerId,PortalId));
                    ADNPage.Redirect(Url,true);
                }
            }
			if (PortalsTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid2_ItemCommand END.",PortalsTrace.Sw.Info);
        }
      
        #endregion Grid methods

        public override void Page_PreInit(object sender, EventArgs e)
        {
            // Add a link for the edit page
            AddText             = "ADD_PORTAL";
            AddUrl              = Config.ModulesPath + "/PortalsAdmin/AddNewPortal.aspx";
            base.Page_PreInit(sender, e);
        }

        override protected void OnInit(EventArgs e)
		{
			base.OnInit(e);
			InitializeComponent();
        }
		private void InitializeComponent() 
		{    
			Load                            +=  new EventHandler(Page_Load);
            RadGrid1.DetailTableDataBind    +=  new GridDetailTableDataBindEventHandler(RadGrid1_DetailTableDataBind);
            RadGrid1.NeedDataSource         +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.DeleteCommand          +=  new GridCommandEventHandler(RadGrid1_DeleteCommand);
            RadGrid1.ItemCommand            +=  new GridCommandEventHandler(RadGrid1_ItemCommand);
            RadGrid1.InsertCommand          +=  new GridCommandEventHandler(RadGrid1_InsertCommand);
            RadGrid1.UpdateCommand          +=  new GridCommandEventHandler(RadGrid1_UpdateCommand);
            RadGrid1.ItemDataBound          +=  new GridItemEventHandler(RadGrid1_ItemDataBound);
            
            RadGrid2.NeedDataSource         +=  new GridNeedDataSourceEventHandler(RadGrid2_NeedDataSource);
            RadGrid2.ItemDataBound          +=  new GridItemEventHandler(RadGrid2_ItemDataBound);
            RadGrid2.DeleteCommand          +=  new GridCommandEventHandler(RadGrid2_DeleteCommand);
            RadGrid2.InsertCommand          +=  new GridCommandEventHandler(RadGrid2_InsertCommand);
            RadGrid2.ItemCommand            +=  new GridCommandEventHandler(RadGrid2_ItemCommand);

            RadGrid1.SelectedIndexChanged   +=  new EventHandler(RadGrid1_SelectedIndexChanged);
            RadGrid1.DataBound              +=  new EventHandler(RadGrid1_DataBound);
 		}
    }
}